{js:kindeditor}
{js:my97date}
{js:fileUpload}
{set:$seller_id = $this->seller['seller_id']}
<h1 class="page_title">商品编辑</h1>
<section class="goods_tab">
	<ul>
		<li class="on">商品信息</li>
		<li>商品描述</li>
		<li>SEO优化</li>
	</ul>
</section>
<section class="input_li">
	<form action="{url:/seller/goods_update}" name="goodsForm" method="post" novalidate="true">
		<input type="hidden" name="id" value="0" />
		<input type='hidden' name="img" value="" />
		<input type='hidden' name="_imgList" value="" />
		<input type='hidden' name="callback" value="{echo:IUrl::getRefRoute()}" />
		<ul class="goods_con_1 goods_con">
			<li>
				<span class="input_item">商品名称 <em>*</em></span>
				<input name="name" type="text" class="input_text" value="" initmsg="商品名称填写正确" pattern="required" alt="商品名称不能为空" />
			</li>
			<li>
				<span class="input_item">关键词 <em>英文逗号分隔，每词不超过15个字符</em></span>
				<input name="search_words" type="text" class="input_text"  />
			</li>
			<li>
				<span class="input_item">所属分类 <em>*</em></span>
				<input class="input_btn" type="button" name="_goodsCategoryButton" value="点击设置分类" />
				<div class="categoryBox" id="__categoryBox"></div>
				{set:plugin::trigger('goodsCategoryWidget',array("type" => "checkbox","name" => "_goods_category[]","value" => isset($goods_category) ? $goods_category : ""))}
			</li>
			<li>
				<span class="input_item">商品排序 <em>*</em></span>
				<input name="sort" type="text" class="input_text" pattern="int" value="99" />
			</li>
			<li>
				<span class="input_item">计件单位显示 <em>*</em></span>
				<input name="unit" type="text" class="input_text" value="件"/>
			</li>
			<li>
				<span class="li_item">是否免运费：</span>
				<label class="input_radio"><input type='radio' name='is_delivery_fee' value='1'  /><span>是</span></label>
				<label class="input_radio"><input type='radio' name='is_delivery_fee' value='0' checked="checked" /><span>否</span></label>
			</li>
			<li>
				<span class="input_item">基本数据 <em>*</em></span>
				<div class="base_info">
					<table class="goods_table">
						<thead id="goodsBaseHead"></thead>
						<tbody id="goodsBaseBody"></tbody>

						<!--商品标题模板-->
						<script id="goodsHeadTemplate" type='text/html'>
						<tr>
							<th>商品货号</th>
							<%var isProduct = false;%>
							<%for(var item in templateData){%>
							<%isProduct = true;%>
							<th><a href="javascript:confirm('确定要删除此列规格？','delSpec(<%=templateData[item]['id']%>)');"><%=templateData[item]['name']%>【删】</a></th>
							<%}%>
							<th>库存</th>
							<th>市场价格</th>
							<th>销售价格</th>
							<th>成本价格</th>
							<th>重量(克)</th>
							<%if(isProduct == true){%>
							<th>操作</th>
							<%}%>
						</tr>
						</script>

						<!--商品内容模板-->
						<script id="goodsRowTemplate" type="text/html">
						<%var i=0;%>
						<%for(var item in templateData){%>
						<%item = templateData[item]%>
						<tr>
							<td><input class="text" name="_goods_no[<%=i%>]" pattern="required" type="text" value="<%=item['goods_no'] ? item['goods_no'] : item['products_no']%>" /></td>
							<%var isProduct = false;%>
							<%var specArrayList = typeof item['spec_array'] == 'string' && item['spec_array'] ? JSON().parse(item['spec_array']) : item['spec_array'];%>
							<%for(var result in specArrayList){%>
							<%result = specArrayList[result]%>
							<input type='hidden' class="text" name="_spec_array[<%=i%>][]" value='<%=JSON().stringify(result)%>' />
							<%isProduct = true;%>
							<td>
								<%if(result['type'] == 1){%>
									<%=result['value']%>
								<%}else{%>
									<img class="img_border" width="30px" height="30px" src="<%=webroot(result['value'])%>">
								<%}%>
							</td>
							<%}%>
							<td><input class="text" name="_store_nums[<%=i%>]" type="text" pattern="int" value="<%=item['store_nums']?item['store_nums']:100%>" /></td>
							<td><input class="text" name="_market_price[<%=i%>]" type="text" pattern="float" value="<%=item['market_price']%>" /></td>
							<td>
								<input type='hidden' name="_groupPrice[<%=i%>]" value="<%=item['groupPrice']%>" />
								<input class="text" name="_sell_price[<%=i%>]" type="text" pattern="float" value="<%=item['sell_price']%>" />
								<input class="button" type="button" onclick="memberPrice(this);" value="会员组价格 <%if(item['groupPrice']){%>*<%}%>" />
							</td>
							<td><input class="text" name="_cost_price[<%=i%>]" type="text" pattern="float" empty value="<%=item['cost_price']%>" /></td>
							<td><input class="text" name="_weight[<%=i%>]" type="text" pattern="float" empty value="<%=item['weight']%>" /></td>
							<%if(isProduct == true){%>
							<td><span class="del" onclick="delProduct(this);">删除</span></td>
							<%}%>
						</tr>
						<%i++;%>
						<%}%>
						</script>
					</table>
				</div>
			</li>
			<li>
				<span class="input_item">商品模型 <em>*</em></span>
				<select name="model_id" class="input_select" onchange="create_attr(this.value)">
					<option value="0">通用类型 </option>
					{query:name=model}
					<option value="{$item['id']}">{$item['name']}</option>
					{/query}
				</select>
			</li>
			<li id="properties" style="display:none">
				<span class="input_item">扩展属性 <em>*</em></span>
				<table class="properties_table" id="propert_table">
				</table>
				<!--商品属性模板 开始-->
				<script type='text/html' id='propertiesTemplate'>
				<%for(var item in templateData){%>
				<%item = templateData[item]%>
				<%var valueItems = item['value'].split(',');%>
				<tr>
					<th><%=item["name"]%>：</th>
					<td>
						<%if(item['type'] == 1){%>
							<%for(var tempVal in valueItems){%>
							<%tempVal = valueItems[tempVal]%>
							<label class="input_radio">
								<input type="radio" name="attr_id_<%=item['id']%>" value="<%=tempVal%>" /><span><%=tempVal%></span>
							</label>
							<%}%>
						<%}else if(item['type'] == 2){%>
							<%for(var tempVal in valueItems){%>
							<%tempVal = valueItems[tempVal]%>
							<label class="input_radio">
								<input type="checkbox" name="attr_id_<%=item['id']%>[]" value="<%=tempVal%>"/><span><%=tempVal%></span>
							</label>
							<%}%>
						<%}else if(item['type'] == 3){%>
							<select class="input_select" name="attr_id_<%=item['id']%>">
							<%for(var tempVal in valueItems){%>
							<%tempVal = valueItems[tempVal]%>
							<option value="<%=tempVal%>"><%=tempVal%></option>
							<%}%>
							</select>
						<%}else if(item['type'] == 4){%>
							<input type="text" name="attr_id_<%=item['id']%>" value="<%=item['value']%>" class="input_text" />
						<%}%>
					</td>
				</tr>
				<%}%>
				</script>
				<!--商品属性模板 结束-->
			</li>
			<li>
				<span class="input_item">规格</span>
				<input class="input_btn" type="button" onclick="selSpec()" value="添加规格" />
			</li>
			<li>
				<span class="input_item">商品品牌</span>
				<select class="input_select" name="brand_id">
					<option value="0">请选择</option>
					{query:name=brand}
					<option value="{$item['id']}">{$item['name']}</option>
					{/query}
				</select>
			</li>
			<li>
				<span class="li_item">商品状态：</span>
				<label class="input_radio"><input type='radio' name='is_del' value='3' checked="checked" /><span>上架</span></label>
				<label class="input_radio"><input type='radio' name='is_del' value='2' /><span>下架</span></label>
			</li>
			<li>
				<span class="input_item">产品相册</span>
				<label class="input_btn">选择图片<input id="fileUpload" type="file" accept="image/png,image/gif,image/jpeg" name="_goodsFile" multiple="multiple" data-url="{url:/goods/goods_img_upload/seller_id/$seller_id}" style="display:none;" /></label>
				<div class="goods_img">
					<div class="tip" id="uploadPercent">可传多张图片，分辨率3000px以下，大小不得超过{echo:IUpload::getMaxSize()}</div>
					<div class="pic_box" id="thumbnails"></div>

					<!--图片模板-->
					<script type='text/html' id='picTemplate'>
					<span class='pic'>
						<img name="picThumb" onclick="defaultImage(this);" src="<%=webroot(picRoot)%>" alt="<%=picRoot%>" />
						<p>
							<span onclick="$(this).parents('.pic').insertBefore($(this).parents('.pic').prev());">前移</span>
							<span onclick="$(this).parents('.pic').remove();">删除</span>
							<span onclick="$(this).parents('.pic').insertAfter($(this).parents('.pic').next());">后移</span>
						</p>
					</span>
					</script>
				</div>
			</li>
		</ul>
		<ul class="goods_con_2 goods_con none">
			<li><textarea id="content" name="content" style="width:100%;height:400px;"></textarea></li>
		</ul>
		<ul class="goods_con_3 goods_con none">
			<li>
				<span class="input_item">SEO关键词</span>
				<input name="keywords" class="input_text" type="text" value="" />
			</li>

			<li>
				<span class="input_item">SEO描述</span>
				<textarea name="description" class="input_textarea"></textarea>
			</li>
		</ul>
		<ul>
			<li>
				<input type="submit" class="input_submit" value="确 定" onclick="return checkForm()" />
			</li>
		</ul>
	</form>
</section>


<script language="javascript">
//创建表单实例
var formObj = new Form('goodsForm');

//默认货号
var defaultProductNo = '{echo:goods_class::createGoodsNo()}';

$(function()
{
	$(".goods_tab").on("click","li", function() {
		var t = $(this), i = t.index()+1;
		t.addClass("on").siblings("li").removeClass("on");
		$(".goods_con").hide();
		$(".goods_con_"+i).show();
	})
	//商品图片的回填
	{if:isset($goods_photo)}
	var goodsPhoto = {echo:JSON::encode($goods_photo)};
	for(var item in goodsPhoto)
	{
		var picHtml = template.render('picTemplate',{'picRoot':goodsPhoto[item].img});
		$('#thumbnails').append(picHtml);
	}
	{/if}

	//商品默认图片
	{if:isset($form['img']) && $form['img']}
	$('#thumbnails img[name="picThumb"][alt="{echo:$form['img']}"]').addClass('current');
	{/if}

	initProductTable();

	//存在商品信息
	{if:isset($form)}
	var goods = {echo:JSON::encode($form)};

	var goodsRowHtml = template.render('goodsRowTemplate',{'templateData':[goods]});
	$('#goodsBaseBody').html(goodsRowHtml);

	formObj.init(goods);

	//模型选择
	$('[name="model_id"]').change();
	{else:}
	$('[name="_goods_no[0]"]').val(defaultProductNo);
	{/if}

	//存在货品信息,进行数据填充
	{if:isset($product)}
	var spec_array = {echo:$product[0]['spec_array']};
	var product    = {echo:JSON::encode($product)};

	var goodsHeadHtml = template.render('goodsHeadTemplate',{'templateData':spec_array});
	$('#goodsBaseHead').html(goodsHeadHtml);

	var goodsRowHtml = template.render('goodsRowTemplate',{'templateData':product});
	$('#goodsBaseBody').html(goodsRowHtml);
	{/if}

	//编辑器载入
	KindEditorObj = KindEditor.create('#content',{
		"filterMode":false,
		"designMode":true,
		"items" : [
			'source', '|','fontname', 'fontsize', '|', 'forecolor',  'bold', 'italic', 'underline',
			'removeformat', '|', 'emoticons', 'image', 'link'
		],

	});

	//jquery图片上传
    $('[name="_goodsFile"]').fileupload({
        dataType: 'json',
        done: function (e, data)
        {
        	if(data.result && data.result.flag == 1)
        	{
        		uploadPicCallback(data.result);
        	}
        	else
        	{
        		realAlert("上传失败");
        	}
        },
        progressall: function (e, data)
        {
            var progress = parseInt(data.loaded / data.total * 100);
            $('#uploadPercent').text("加载完成："+progress+"%");
        }
    });
});

//初始化货品表格
function initProductTable()
{
	//默认产生一条商品标题空挡
	var goodsHeadHtml = template.render('goodsHeadTemplate',{'templateData':[]});
	$('#goodsBaseHead').html(goodsHeadHtml);

	//默认产生一条商品空挡
	var goodsRowHtml = template.render('goodsRowTemplate',{'templateData':[[]]});
	$('#goodsBaseBody').html(goodsRowHtml);
}

//删除货品
function delProduct(_self)
{
	$(_self).parent().parent().remove();
	if($('#goodsBaseBody tr').length == 0)
	{
		initProductTable();
	}
}

//提交表单前的检查
function checkForm()
{
	//整理商品图片
	var goodsPhoto = [];
	$('#thumbnails img[name="picThumb"]').each(function(){
		goodsPhoto.push(this.alt);
	});
	if(goodsPhoto.length > 0)
	{
		$('input[name="_imgList"]').val(goodsPhoto.join(','));
		$('input[name="img"]').val($('#thumbnails img[name="picThumb"][class="current"]').attr('alt'));
	}
	return true;
}


//添加规格
function selSpec()
{
	//货品是否已经存在
	var tempUrl  = $('input:hidden[name^="_spec_array"]').length > 0 ? '{url:/goods/search_spec/seller_id/@seller_id@}' : '{url:/goods/search_spec/model_id/@model_id@/goods_id/@goods_id@/seller_id/@seller_id@}';
	var model_id = $('[name="model_id"]').val();
	var goods_id = $('[name="id"]').val();
	var seller_id= {$seller_id};

	tempUrl = tempUrl.replace('@model_id@',model_id);
	tempUrl = tempUrl.replace('@goods_id@',goods_id);
	tempUrl = tempUrl.replace('@seller_id@',seller_id);

	art.dialog.open(tempUrl,{
		title:'设置商品的规格',
		okVal:'保存',
		{if:IClient::getDevice() == 'mobile'}
		width:'97%',
		{/if}
		ok:function(iframeWin, topWin)
		{
			//添加的规格
			var addSpecObject = $(iframeWin.document).find('[id^="vertical_"]');
			if(addSpecObject.length == 0)
			{
				return;
			}

			var specIsHere    = getIsHereSpec();
			var specValueData = specIsHere.specValueData;
			var specData      = specIsHere.specData;

			//追加新建规格
			addSpecObject.each(function()
			{
				$(this).find('input:hidden[name="specJson"]').each(function()
				{
					var json = $.parseJSON(this.value);
					if(!specValueData[json.id])
					{
						specData[json.id]      = json;
						specValueData[json.id] = [];
					}
					specValueData[json.id].push({"tip":json.tip,"value":json.value});
				});
			});
			createProductList(specData,specValueData);
		}
	});
}

//笛卡儿积组合
function descartes(list,specData)
{
	//parent上一级索引;count指针计数
	var point  = {};

	var result = [];
	var pIndex = null;
	var tempCount = 0;
	var temp   = [];

	//根据参数列生成指针对象
	for(var index in list)
	{
		if(typeof list[index] == 'object')
		{
			point[index] = {'parent':pIndex,'count':0}
			pIndex = index;
		}
	}

	//单维度数据结构直接返回
	if(pIndex == null)
	{
		return list;
	}

	//动态生成笛卡尔积
	while(true)
	{
		for(var index in list)
		{
			tempCount = point[index]['count'];
			var itemSpecData = list[index][tempCount];
			temp.push({"id":specData[index].id,"type":specData[index].type,"name":specData[index].name,"value":itemSpecData.value,"tip":itemSpecData.tip});
		}

		//压入结果数组
		result.push(temp);
		temp = [];

		//检查指针最大值问题
		while(true)
		{
			if(point[index]['count']+1 >= list[index].length)
			{
				point[index]['count'] = 0;
				pIndex = point[index]['parent'];
				if(pIndex == null)
				{
					return result;
				}

				//赋值parent进行再次检查
				index = pIndex;
			}
			else
			{
				point[index]['count']++;
				break;
			}
		}
	}
}

//根据模型动态生成扩展属性
function create_attr(model_id)
{
	$.getJSON("{url:/block/attribute_init}",{'model_id':model_id}, function(json)
	{
		if(json && json.length > 0)
		{
			var templateHtml = template.render('propertiesTemplate',{'templateData':json});
			$('#propert_table').html(templateHtml);
			$('#properties').show();

			//表单回填设置项
			{if:isset($goods_attr)}
			{set:$attrArray = array();}
			{foreach:items = $goods_attr}
			{set:$valArray = explode(',',$item);}
			{set:$attrArray[] = '"attr_id_'.$key.'[]":"'.join(";",$valArray).'"'}
			{set:$attrArray[] = '"attr_id_'.$key.'":"'.join(";",$valArray).'"'}
			{/foreach}
			formObj.init({{echo:join(',',$attrArray)}});
			{/if}
		}
		else
		{
			$('#properties').hide();
		}
	});
}

/**
 * 图片上传回调,handers.js回调
 * @param picJson => {'flag','img','list','show'}
 */
function uploadPicCallback(picJson)
{
	var picHtml = template.render('picTemplate',{'picRoot':picJson.img});
	$('#thumbnails').append(picHtml);

	//默认设置第一个为默认图片
	if($('#thumbnails img[name="picThumb"][class="current"]').length == 0)
	{
		$('#thumbnails img[name="picThumb"]:first').addClass('current');
	}
}

/**
 * 设置商品默认图片
 */
function defaultImage(_self)
{
	$('#thumbnails img[name="picThumb"]').removeClass('current');
	$(_self).addClass('current');
}

/**
 * 会员价格
 * @param obj 按钮所处对象
 */
function memberPrice(obj)
{
	var sellPrice = $(obj).siblings('input[name^="_sell_price"]')[0].value;
	if($.isNumeric(sellPrice) == false)
	{
		alert('请先设置商品的价格再设置会员价格');
		return;
	}

	var groupPriceValue = $(obj).siblings('input[name^="_groupPrice"]');

	//用户组的价格
	art.dialog.data('groupPrice',groupPriceValue.val());

	//开启新页面
	var tempUrl = '{url:/goods/member_price/sell_price/@sell_price@/seller_id/$seller_id}';
	tempUrl = tempUrl.replace('@sell_price@',sellPrice);
	art.dialog.open(tempUrl,{
		id:'memberPriceWindow',
	    title: '此商品对于会员组价格',
	    ok:function(iframeWin, topWin)
	    {
	    	var formObject = iframeWin.document.forms['groupPriceForm'];
	    	var groupPriceObject = {};
	    	$(formObject).find('input[name^="groupPrice"]').each(function(){
	    		if(this.value != '')
	    		{
	    			//去掉前缀获取group的ID
		    		var groupId = this.name.replace('groupPrice','');

		    		//拼接json串
		    		groupPriceObject[groupId] = this.value;
	    		}
	    	});

	    	//更新会员价格值
    		var temp = [];
    		for(var gid in groupPriceObject)
    		{
    			temp.push('"'+gid+'":"'+groupPriceObject[gid]+'"');
    		}
    		groupPriceValue.val('{'+temp.join(',')+'}');
    		return true;
		}
	});
}

//删除规格
function delSpec(specId)
{
	$('input:hidden[name^="_spec_array"]').each(function()
	{
		var json = $.parseJSON(this.value);
		if(json.id == specId)
		{
			$(this).remove();
		}
	});

	//当前已经存在的规格数据
	var specIsHere = getIsHereSpec();
	createProductList(specIsHere.specData,specIsHere.specValueData);
}

//获取已经存在的规格
function getIsHereSpec()
{
	//开始遍历规格
	var specValueData = {};
	var specData      = {};

	//规格已经存在的数据
	if($('input:hidden[name^="_spec_array"]').length > 0)
	{
		$('input:hidden[name^="_spec_array"]').each(function()
		{
			var json = $.parseJSON(this.value);
			if(!specValueData[json.id])
			{
				specData[json.id]      = json;
				specValueData[json.id] = [];
			}

			if(jQuery.inArray(json['value'],specValueData[json.id]) == -1)
			{
				specValueData[json.id].push({"tip":json.tip,"value":json.value});
			}
		});
	}
	return {"specData":specData,"specValueData":specValueData};
}

/**
 * @brief 根据规格数据生成货品序列
 * @param object specData规格数据对象
 * @param object specValueData 规格值对象集合
 */
function createProductList(specData,specValueData)
{
	//生成货品的笛卡尔积
	var specMaxData = descartes(specValueData,specData);

	//生成最终的货品数据
	var productList = [];
	for(var i = 0;i < specMaxData.length;i++)
	{
		//从表单中获取默认商品数据
		var productJson = {};
		var defaultIndex = $('#goodsBaseBody tr').length > i ? i : i%$('#goodsBaseBody tr').length;
		$('#goodsBaseBody tr:eq('+defaultIndex+')').find('input[type="text"]').each(function(){
			productJson[this.name.replace(/^_(\w+)\[\d+\]/g,"$1")] = this.value;
		});

		var productItem = {};
		for(var index in productJson)
		{
			//自动组建货品号
			if(index == 'goods_no')
			{
				//值为空时设置默认货号
				if(productJson[index] == '')
				{
					productJson[index] = defaultProductNo;
				}

				if(productJson[index].match(/(?:\-\d*)$/) == null)
				{
					//正常货号生成
					productItem['goods_no'] = productJson[index]+'-'+(i+1);
				}
				else
				{
					//货号已经存在则替换
					productItem['goods_no'] = productJson[index].replace(/(?:\-\d*)$/,'-'+(i+1));
				}
			}
			else
			{
				productItem[index] = productJson[index];
			}
		}
		productItem['spec_array'] = specMaxData[i];
		productList.push(productItem);
	}

	//创建规格标题
	var goodsHeadHtml = template.render('goodsHeadTemplate',{'templateData':specData});
	$('#goodsBaseHead').html(goodsHeadHtml);

	//创建货品数据表格
	var goodsRowHtml = template.render('goodsRowTemplate',{'templateData':productList});
	$('#goodsBaseBody').html(goodsRowHtml);

	if($('#goodsBaseBody tr').length == 0)
	{
		initProductTable();
	}
}
</script>
